<template>
	<!-- 订单页 -->
	<view class="order">
		<!-- 导航栏 -->
		<view class="navbar">
			<view class="navbar-item" :class="{active: activeIndex===0}" @click="activeIndex=0">当前订单</view>
			<view class="navbar-item" :class="{active: activeIndex===1}" @click="activeIndex=1">历史订单</view>
			<!-- 文字底部横条 -->
			<view class="navbar-line" :class="{active: activeIndex===1}"></view>
		</view>

		<!-- 订单列表 -->
		<view class="orderList">
			<!-- 列表 -->
			<u-list @scrolltolower="scrolltolower">
				<!-- 订单卡片 -->
				<u-list-item v-for="order in orderList" :key="order.id">
					<view class="orderList-card">
						<u-cell-group :border="false">
							<!-- 订单状态 -->
							<u-cell title="橘猫の茶" :label="order.createdTime" titleStyle="font-weight: 700;" isLink>
								<template #value>
									<!-- 标题 -->
									<view class="order-title">
										<!-- 倒计时 -->
										<view class="order-deadline" v-if="order.status==1">
											<u-count-down :time="order.remainTime" format="mm:ss"
												@change="onChangeTime">
												<view class="time">
													<view class="time__custom">
														<text
															class="time__custom__item">{{ String(timeData.minutes).padStart(2,'0') }}</text>
													</view>
													<text class="time__doc">:</text>
													<view class="time__custom">
														<text
															class="time__custom__item">{{ String(timeData.seconds).padStart(2,'0') }}</text>
													</view>
												</view>
											</u-count-down>
										</view>
										<view class="order-state">{{order.orderStatus}}</view>
									</view>
								</template>
							</u-cell>
							<!-- 商品信息 -->
							<view class="order-goods">
								<view class="order-goods-item" v-for="good in order.goods_info" :key="good.id">
									<!-- 商品图片 -->
									<view class="order-goods__image">
										<image :src="good.s_goods_photos[0].path" mode="aspectFill"></image>
									</view>
									<!-- 右侧内容 -->
									<view class="order-goods__about">
										<!-- 商品名称与单价 -->
										<view class="order-goods__info">
											<!-- 商品名称 -->
											<view class="order-goods__name">{{good.goods_name}}</view>
											<!-- 商品价格 -->
											<view class="order-goods__price">￥{{good.sale_price}}</view>
										</view>
										<!-- 商品描述与数量 -->
										<view class="order-goods__desc">
											<!-- 商品描述 -->
											<view class="order-goods__desc">默认</view>
											<!-- 商品数量 -->
											<view class="order-goods__num">共{{good.num}}件</view>
										</view>
									</view>
								</view>
							</view>
							<!-- 操作 -->
							<u-cell :title="'合计：￥'+ order.total_price" titleStyle="color: #ff516b;" :border="false">
								<template #value>
									<view class="order-operator">
										<view class="order-button">
											<u-button text="去支付" shape="circle"></u-button>
										</view>
										<view class="order-button">
											<u-button text="删除订单" shape="circle"
												@click="deleteOrder(order.id)"></u-button>
										</view>
									</view>
								</template>
							</u-cell>
						</u-cell-group>
					</view>
				</u-list-item>

				<!-- 底线 -->
				<view class="lastLine" v-if="isOrderFinish">我可是有底线的哟~</view>
			</u-list>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	// 引入自定义函数库
	import utils from '@/utils/index.js';

	export default {
		data() {
			return {
				// 激活了哪个分类：0 当前订单，1 历史订单
				activeIndex: 0,
				// 倒计时时间
				timeData: {},
				// 订单列表
				orderList: [],
				// 后台总订单数
				allOrderNum: null,
				// 当前页数
				nowPage: 1,
			}
		},
		computed: {
			...mapState(['userInfo']),
			// 订单数据是否请求完毕
			isOrderFinish() {
				return this.orderList.length >= this.allOrderNum;
			},
		},
		watch: {
			// 监听选择了哪一订单分类
			activeIndex: {
				handler(value) {
					// 初始化配置
					this.orderList = [];
					this.nowPage = 1;
					// 请求订单列表	
					if (value === 0) return this.getCurrentOrderList();
					if (value === 1) return this.getOrderList();
				},
				immediate: false
			},
		},
		methods: {
			// 倒计时时间改变触发
			onChangeTime(e) {
				this.timeData = e;
			},
			// 日期格式化
			dateFormat(date) {
				if (!date) return '';
				return this.$moment(date).format('YYYY-MM-DD HH:mm:ss');
			},
			// 订单状态转译	
			orderStatusTranslate(status) {
				let code = Number(status);
				if (code === -1) return '已删除';
				const codeMap = ['已过期', '已下单', '已支付', '已发货', '退货中', '退款中', '已完成', '已取消'];
				return codeMap[code];
			},
			// 计算倒计时时间
			computeDeadLine(time) {
				return Number(time) + 30 * 60 * 1000 - new Date();
			},
			// 获取所有订单列表
			async getOrderList(option = {}) {
				let data = await this.$api.order.getOrderListAPI(option);
				// console.log(data.result);
				this.allOrderNum = data.result.count;
				// 处理数据，因为goods_info是JSON格式，需要转成数据
				let tempList = data.result.rows.map(o => {
					return {
						...o,
						goods_info: JSON.parse(o.goods_info),
						createdTime: this.dateFormat(o.createdAt), // 订单日期格式化
						orderStatus: this.orderStatusTranslate(o.status), // 订单状态转译
						remainTime: o.status == 1 ? this.computeDeadLine(o.order_time) : null, // 剩余支付时间
					}
				});
				// 保存订单数据
				this.orderList.push(...tempList);
			},
			// 获取当前订单
			getCurrentOrderList() {
				// 请求队列
				let reqQuene = [];
				// 循环添加请求到请求队列
				for (let i = 1; i <= 5; i++) {
					// 订单状态
					let status = String(i);
					// 将请求添加至请求队列
					reqQuene.push(this.getOrderList({
						status,
						page: this.nowPage
					}));
				}
				this.nowPage++;
				Promise.all(reqQuene);
			},
			// 删除订单
			deleteOrder(id) {
				uni.showModal({
					content: '确认删除该订单？',
					success: async (res) => {
						if (res.confirm) {
							// 删除订单
							let data = await this.$api.order.deleteOrderAPI(id);
							// 延时后重新请求数据
							let timer = setTimeout(() => {
								this.orderList = [];
								this.getOrderList();
							}, 1000);
						}
					}
				});
			},
			// 列表触底事件
			scrolltolower() {
				// 数据获取完全，不用请求
				if (this.isOrderFinish) return;
				// 不完全，再次获取订单列表(防抖处理)
				let fn = this.getOrderList.bind(this, {
					page: this.nowPage
				});
				this.nowPage++;
				uni.$u.debounce(fn, 500);
			}
		},
		async onShow() {
			// 如果用户信息不存在,直接跳出
			if (!this.userInfo && !await utils.reqUserInfoAuth()) return;
			// 获取订单
			this.orderList = [];
			if (this.activeIndex === 0) return this.getCurrentOrderList();
			if (this.activeIndex === 1) return this.getOrderList();
			// this.getCurrentOrderList();
		}
	}
</script>

<style lang="scss" scoped>
	.order {
		@include page-bgc();

		// 导航栏
		.navbar {
			position: relative;
			height: 100rpx;
			width: 100%;
			background-color: #fff;
			display: flex;
			align-items: center;

			.navbar-item {
				flex: 1;
				color: #444444;
				font-size: 30rpx;
				text-align: center;

				&.active {
					color: $theme-color;
				}
			}

			// 文字底部横条
			.navbar-line {
				position: absolute;
				bottom: 12rpx;
				left: 25%;
				transform: translateX(-50%);
				width: 60rpx;
				height: 6rpx;
				border-radius: 3rpx;
				background-color: $theme-color;
				transition: all 0.4s;

				&.active {
					left: 75%;
				}
			}
		}

		// 订单列表
		.orderList {
			height: calc(100vh - 100rpx);
			overflow: auto;
			padding-top: 20rpx;
			box-sizing: border-box;

			// 订单卡片
			.orderList-card {
				@include whiteCard();
				padding: 0 24rpx;

				::v-deep {
					.u-cell__body {
						padding-left: 0;
						padding-right: 0;
					}

					.u-cell__right-icon-wrap {
						margin-bottom: 22px;
					}
				}

				// 标题
				.order-title {
					display: flex;
					align-items: center;
					margin-bottom: 22px;

					// 倒计时
					.order-deadline {
						margin-right: 10px;

						// 自定义日期格式
						.time {
							display: flex;
							align-items: center;
							height: 22px;

							&__custom {
								width: 22px;
								background-color: transparent;
								border-radius: 4px;
								display: flex;
								justify-content: center;
								align-items: center;

								&__item {
									color: $theme-color;
									font-size: 15px;
									text-align: center;
								}
							}

							&__doc {
								color: #000;
								padding: 0 2px;
							}

							&__item {
								color: #606266;
								font-size: 15px;
								margin-right: 4px;
							}
						}
					}

					.order-state {

						// 成功
						&.success {
							color: #0ecb64;
						}

						// 进行中
						&.pending {
							color: orange;
						}

						// 失败
						&.fail {
							color: #f00;
						}
					}
				}

				// 商品信息
				.order-goods {
					// border-bottom: 1px solid #e9eaeb;

					.order-goods-item {
						padding: 10px 0;
						display: flex;

						// 商品图片
						.order-goods__image {
							flex-shrink: 0;
							width: 100rpx;
							height: 100rpx;
							overflow: hidden;

							image {
								width: 100%;
								height: 100%;
							}
						}

						// 右侧内容
						.order-goods__about {
							flex: 1;
							padding-left: 10px;
							display: flex;
							flex-direction: column;
							justify-content: center;

							// 商品名称与单价
							.order-goods__info {
								display: flex;
								align-items: center;
								justify-content: space-between;
								margin-bottom: 4px;

								// 商品名称
								.order-goods__name {
									font-size: 32rpx;
								}

								// 商品价格
								.order-goods__price {
									font-size: 30rpx;
									color: $theme-color;
								}
							}

							// 商品描述与数量
							.order-goods__desc {
								display: flex;
								align-items: center;
								justify-content: space-between;

								// 商品描述
								// 商品数量
								.order-goods__desc,
								.order-goods__num {
									font-size: 26rpx;
									color: #999;
								}
							}
						}
					}
				}

				// 操作
				.order-operator {
					display: flex;
					align-items: center;

					.order-button {
						width: 180rpx;
						margin-left: 20rpx;

						::v-deep .u-button {
							height: 56rpx;
						}
					}
				}
			}

			// 底线
			.lastLine {
				padding: 36rpx;
				color: #999;
				font-size: 28rpx;
				text-align: center;
			}
		}
	}
</style>